import React, { useState, ChangeEvent } from "react";

interface FileInfo {
  name: string;
  size: number;
  type: string;
}

const FileUpload: React.FC = () => {
  const [progress, setProgress] = useState<number>(0);
  const [uploading, setUploading] = useState<boolean>(false);
  const [uploadedFile, setUploadedFile] = useState<FileInfo | null>(null);
  const CHUNK_SIZE = 5 * 1024 * 1024; // 5MB

  const mockUploadChunk = async (chunk: Blob, index: number, total: number) => {
    await new Promise((resolve) => setTimeout(resolve, 500));
    return { success: true, index };
  };

  const handleFileUpload = async (e: ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (!file) return;

    setUploading(true);
    try {
      const chunks: Blob[] = [];
      let start = 0;
      while (start < file.size) {
        const end = Math.min(start + CHUNK_SIZE, file.size);
        chunks.push(file.slice(start, end));
        start = end;
      }
      const totalChunks = chunks.length;

      let uploadedChunks = 0;
      for (let i = 0; i < totalChunks; i++) {
        await mockUploadChunk(chunks[i], i, totalChunks);
        uploadedChunks++;
        setProgress(Math.round((uploadedChunks / totalChunks) * 100));
      }

      setUploadedFile({
        name: file.name,
        size: file.size,
        type: file.type,
      });
      alert("上传成功");
    } catch (error) {
      console.error("上传失败:", error);
      alert("上传失败");
    } finally {
      setUploading(false);
    }
  };

  return (
    <div style={{
      maxWidth: "500px",
      margin: "2rem auto",
      padding: "2rem",
      boxShadow: "0 0 10px rgba(0,0,0,0.1)"
    }}>
      <h2>文件上传</h2>

      {/* 文件上传输入 */}
      <div style={{ margin: "2rem 0" }}>
        <input
          type="file"
          onChange={handleFileUpload}
          disabled={uploading}
          accept="*/*"
        />
      </div>

      {/* 上传进度 */}
      {uploading && (
        <div style={{ margin: "1rem 0" }}>
          <progress value={progress} max="100" /> {progress}%
        </div>
      )}

      {/* 上传结果展示 */}
      {uploadedFile && (
        <div style={{ marginTop: "1rem" }}>
          <h3>上传成功</h3>
          <p>文件名: {uploadedFile.name}</p>
          <p>文件类型: {uploadedFile.type}</p>
          <p>文件大小: {(uploadedFile.size / 1024 / 1024).toFixed(2)} MB</p>
        </div>
      )}
    </div>
  );
};

export default FileUpload;